<template>
  <div class="container">
    <el-dialog
      title="添加管理员"
      :visible.sync="dialogVisible"
      :before-close="handleClose"
    >
      <el-form ref="addForm" label-width="100px" label-position="right" :rules="addFormRules" :model="addForm">
        <el-form-item label="用户名" prop="adminName">
          <el-input v-model="addForm.adminName" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password" />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPass">
          <el-input v-model="addForm.confirmPass" />
        </el-form-item>
        <el-form-item label="账号角色" prop="fkRoleId">
          <el-select v-model="addForm.fkRoleId" placeholder="请选择角色" style="width:100%">
            <template v-for="(item) in roleList">
              <el-option v-if="item.roleName == 'ROLE_DATA'" :key="item.id" label="数据分析员" :value="item.id" />
              <el-option v-else-if="item.roleName == 'ROLE_BOOK'" :key="item.id" label="图书管理员" :value="item.id" />
              <el-option v-else-if="item.roleName == 'ROLE_ORDER'" :key="item.id" label="订单管理员" :value="item.id" />
            </template>

          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelAddAdmin('addForm')">取 消</el-button>
        <el-button type="primary" @click="doAddAdmin('addForm')">确 定</el-button>
      </span>
    </el-dialog>
    <div class="search-add-div">
      <div style="width:500px">
        <el-input v-model="searchStr" placeholder="请输入搜索内容" class="input-with-select">
          <el-select slot="prepend" v-model="searchSelect" placeholder="请选择" style="width:120px">
            <el-option label="全部" value="0" />
            <el-option label="用户名" value="1" />
            <el-tooltip class="item" effect="dark" content="填写：admin、book、data、order" placement="right">
              <el-option label="角色" value="2" />
            </el-tooltip>
          </el-select>
          <el-button slot="append" icon="el-icon-search" @click="search" />
        </el-input>
      </div>

      <div>
        <el-button type="primary" @click="addAdmin">添加管理员</el-button>
      </div>
    </div>
    <el-table
      :data="showAdminList"
      style="width: 100%"
    >
      <el-table-column
        prop="adminName"
        label="用户名"
      />
      <el-table-column
        label="角色"
      >
        <template slot-scope="scope">
          <span v-if="scope.row.roles.roleName === 'ROLE_ADMIN'">超级管理员</span>
          <span v-else-if="scope.row.roles.roleName === 'ROLE_BOOK'">图书管理员</span>
          <span v-else-if="scope.row.roles.roleName === 'ROLE_ORDER'">订单管理员</span>
          <span v-else-if="scope.row.roles.roleName === 'ROLE_DATA'">数据分析员</span>
          <span v-else>暂无</span>
        </template>
      </el-table-column>
      <el-table-column
        label="状态"
      >
        <template slot-scope="scope">
          <el-tag v-if="scope.row.enabled == true">启用</el-tag>
          <el-tag v-else type="danger">禁用</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <div v-if="scope.row.id === adminInfo.id">
            <el-button
              size="mini"
              type="primary"
              :disabled="true"
              @click="handleEnabled(scope.$index, scope.row)"
            >启用</el-button>
            <el-button
              size="mini"
              type="danger"
              :disabled="true"
              @click="handleDisabled(scope.$index, scope.row)"
            >禁用</el-button>
          </div>
          <div v-else-if="scope.row.roles.roleName === 'ROLE_ADMIN'">
            <el-button
              size="mini"
              type="primary"
              :disabled="true"
              @click="handleEnabled(scope.$index, scope.row)"
            >启用</el-button>
            <el-button
              size="mini"
              type="danger"
              :disabled="true"
              @click="handleDisabled(scope.$index, scope.row)"
            >禁用</el-button>
          </div>
          <div v-else>
            <el-button
              size="mini"
              type="primary"
              @click="handleEnabled(scope.$index, scope.row)"
            >启用</el-button>
            <el-button
              size="mini"
              type="danger"
              @click="handleDisabled(scope.$index, scope.row)"
            >禁用</el-button>
          </div>

        </template>
      </el-table-column>
    </el-table>
  </div>
</template>
<script>
import * as admin from '@/api/user'
export default {
  data() {
    const validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'))
      } else {
        callback()
      }
    }

    const validateConfirmPass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请确认密码'))
      } else {
        if (value !== this.addForm.password) {
          return callback(new Error('密码不一致'))
        }
        callback()
      }
    }
    return {
      adminList: [],
      showAdminList: [],
      searchSelect: '0',
      searchStr: '',
      adminInfo: '',
      dialogVisible: false,
      roleList: [{
        id: 1,
        roleName: 'ROLE_ADMIN'
      }, {
        id: 2,
        roleName: 'ROLE_ORDER'
      }, {
        id: 3,
        roleName: 'ROLE_BOOK'
      }, {
        id: 4,
        roleName: 'ROLE_DATA'
      }],
      addForm: {
        adminName: '',
        password: '',
        confirmPass: '',
        fkRoleId: ''
      },
      // 要求8-20位字母，数字，不能含有标点符号
      addFormRules: {
        adminName: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
        password: [{ required: true, validator: validatePass, trigger: 'blur' }],
        confirmPass: [{ required: true, validator: validateConfirmPass, trigger: 'blur' }],
        fkRoleId: [{ required: true, message: '请选择角色', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.getAdmin()
    this.getAdminInfo()
    this.getRoleList()
  },
  methods: {
    getRoleList() {
      admin.getRoleList().then(res => {
        this.roleList = res.object
        // console.log(this.roleList)
      })
    },
    doAddAdmin(formName) {
      // 验证是否合法
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$confirm('确认添加', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            admin.addAdmin(this.addForm).then(res => {
              this.$notify({
                title: '成功',
                message: '操作成功',
                type: 'success'
              })
              this.$refs[formName].resetFields()
              this.dialogVisible = false
              this.getAdmin()
            })
          }).catch(() => {
            // this.$message({
            //   type: 'info',
            //   message: '已取消删除'
            // })
          })
        } else {
          // console.log('error submit!!')
          return false
        }
      })
    },
    cancelAddAdmin(formName) {
      this.dialogVisible = false
      this.$refs[formName].resetFields()
    },
    addAdmin() {
      this.dialogVisible = true
    },
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done()
          this.$refs['addForm'].resetFields()
        })
        .catch(_ => {})
      // done()
    },
    getAdminInfo() {
      admin.getAdminInfo().then(res => {
        this.adminInfo = res.object
      })
    },
    getAdmin() {
      admin.getAdminList().then(res => {
        this.adminList = res.object
        this.showAdminList = res.object
      })
    },
    search() {
      // console.log(this.searchSelect)
      // console.log(this.searchStr)
      if (this.checkSearch()) {
        this.doSearch(this.searchSelect, this.searchStr)
      } else {
        this.$message.warning('请输入搜索内容')
      }
    },
    checkSearch() {
      if (this.searchStr && this.searchSelect) {
        return true
      } else if (this.searchSelect === '0') {
        return true
      } else {
        return false
      }
    },
    doSearch(type, str) {
      let arr = []
      if (type === '0') {
        this.showAdminList = this.adminList
        return
      } else if (type === '1') {
        // 搜索用户名
        arr = this.adminList.filter(element => {
          if (element.adminName.includes(str)) {
            // console.log('sssss')
            return true
          }
        })
        console.log(arr)
      } else if (type === '2') {
        // 搜索角色
        // admin，book，data，order
        let role = ''
        if (str === 'admin') {
          role = 'ROLE_ADMIN'
        } else if (str === 'book') {
          role = 'ROLE_BOOK'
        } else if (str === 'data') {
          role = 'ROLE_DATA'
        } else if (str === 'order') {
          role = 'ROLE_ORDER'
        }
        arr = this.adminList.filter(element => {
          if (!element.roles) {
            return false
          } else if (element.roles.roleName === role) {
            return true
          }
        })
      }

      this.showAdminList = arr
      // console.log(this.showAdminList)
    },
    getUser() {
      admin.getadminList().then(res => {
        // console.log(res)
        this.adminList = res.object
        // console.log(res.object)
        this.showAdminList = res.object
      })
    },
    handleEdit() {

    },
    handleEnabled(index, obj) {
      // eslint-disable-next-line eqeqeq
      if (this.showAdminList[index].enabled == true) {
        this.$message.warning('当前已是启用状态')
      } else {
        const adminQo = {
          id: obj.id,
          enabled: 1
          // adminName: obj.adminName
        }
        admin.setAdminStatus(adminQo).then(res => {
          this.showAdminList[index].enabled = true
          this.$message.success('操作成功')
          this.adminList.forEach(element => {
            if (element.id === obj.id) {
              element.enabled = 1
            }
          })
        }).catch(() => {

        })
      }
    },
    handleDisabled(index, obj) {
      // eslint-disable-next-line eqeqeq
      if (this.showAdminList[index].enabled == 0) {
        this.$message.warning('当前已是禁用状态')
      } else {
        const adminQo = {
          id: obj.id,
          enabled: 0
          // adminName: obj.adminName
        }
        admin.setAdminStatus(adminQo).then(res => {
          this.showAdminList[index].enabled = false
          this.$message.success('操作成功')
          this.adminList.forEach(element => {
            if (element.id === obj.id) {
              element.enabled = 0
            }
          })
        }).catch(() => {

        })
      }
    }

  }
}
</script>

<style scoped lang='scss'>
.container{
  padding: 20px 80px;
}
.search-add-div{
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}
</style>
